package com.tgy.algorithm.base._数组和;

import java.util.HashMap;

public class _整数的数组和 {


    /**
     *
     *   // 1   4
     *  [1,3,1,-1,10,2,11]
     *  [1,0]
     *  [4,1]
     *  [5,2]
     *  [4,3]
     *  [13,4]
     *
     * @param nums
     * @param k
     * @return
     */
    public static int integerSum(int[] nums, int k) {

        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        // 总数为 0 的在-1位置，这个很重要
        map.put(0,-1);
        int maxLen = 0;
        int sum = 0;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
            int preVal = k - sum;
            if (map.containsKey(preVal)) {
                Integer index = map.get(preVal);
                maxLen = Math.max(maxLen,i - index);
            }

            if (!map.containsKey(sum)) {
                map.put(sum,i);
            }
        }

        return maxLen;
    }

    public static void main(String[] args) {

        int[] nums = {2,1,-1,2,1,3,1,2};
        int maxLen = integerSum(nums, 2);
        System.out.println(maxLen);
    }
}
